const _ = require('lodash');
module.exports = app => {
  return async (ctx, next) => {
    const {socket, logger} = ctx;
    const id = socket.id;
    let {token} = ctx.query;

    const kick = (id, msg) => {
      logger.debug('#socket.io tick', id, msg);

      // 踢出用户前发送消息
      socket.emit('connect_error', msg);

      // 调用 adapter 方法踢出用户，客户端触发 disconnect 事件
      socket.disconnect();
    };

    if (_.isEmpty(token))
      return kick(id, '客户端 缺少Token 不允许连接');

    const vps = await app.model.Vps.findOne({where: {token}});
    if (!vps)
      return kick(id, 'Token不存在');

    vps.update(
        {
          status: 4,
          status_num: {
            spider: {finish: 0, wait: 0, error: 0},
            save: {finish: 0, wait: 0, error: 0},
          },
          socket_id: id,
        });

    const [room_queue] = await Promise.all([
      app.model.Config.get('room_queue', 30),
    ]);

    const redis = app.config.redis.client;
    const mysql = app.config.sequelize;
    const mysqlConfig = {
      host: mysql.host,
      port: mysql.port,
      database: mysql.database,
      user: mysql.username,
      password: mysql.password,
    };
    const redisUrl = 'redis://:' + redis.password + '@' + redis.host +
        ':' + redis.port + '/' + redis.db;

    //发送配置给客户端
    socket.emit('config', {room_queue, mysqlConfig, redisUrl});

    socket.on('disconnect', async () => {
      console.log('爬虫断开链接');
      vps.update({
        status: -2,
        socket_id: null,
      });
    });
    await next();
  };
};